<?php
/**
 * 验证码类
 */

namespace app\common\lib;

use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use think\facade\Session;

class Captcha
{
    private static $defualt_code = 'manage_captcha';

    private static $bg = [243, 251, 254];
    private static $charset_num = '0123456789';
    private static $charset_letter = 'abcdefghijklmnopqrstuvwxyz';

    /**
     * 生成图片验证码
     * @param string $captchCode
     * @param array $param
     * @date 2021-01-21 9:48
     */
    static public function create(string $captchaCode = '', array $param = [])
    {
        $length = $param['length'] ?? 4;
        $charsetType = $param['charset'] ?? 3;
        $charsetType = in_array($charsetType, [1, 2, 3]) ? $charsetType : 1;
        $charset = self::$charset_num . self::$charset_letter . strtoupper(self::$charset_letter);

        switch ($charsetType) {
            case 1:
                $charset = self::$charset_num;
                break;
            case 2:
                $charset = self::$charset_letter;
                break;
        }

        $phrase = new PhraseBuilder;

        // 设置验证码位数
        $code = $phrase->build($length, $charset);

        // 生成验证码图片的Builder对象，配置相应属性
        $builder = new CaptchaBuilder($code, $phrase);

        // 设置背景颜色
        $builder->setBackgroundColor(self::$bg[0], self::$bg[1], self::$bg[2]);
//        $builder->setMaxAngle(15);
//        $builder->setMaxBehindLines(0);
//        $builder->setMaxFrontLines(0);

        //设置图片宽高及字体
        $width = $param['width'] ?? 100;
        $height = $param['height'] ?? 40;
        $builder->build($width, $height, $font = null);

        //获取验证码的内容
        $phrase = strtolower($builder->getPhrase());
        $code = self::createSessionCode($captchaCode);
        Session::set($code, $phrase);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-type: image/jpeg');
        $builder->output();
    }

    /**
     * 验证
     * @param $val
     * @param string $captchCode
     * @return bool
     * @date 2021-01-21 10:24
     */
    static public function check($val, $captchCode = '')
    {
        $code = self::createSessionCode($captchCode);
        $storageVale = strtolower(session($code));
        Session::delete($code);
        if (!$storageVale) {
            return false;
        }
        if ($storageVale !== strtolower($val)) {
            return false;
        }
        return true;
    }

    /**
     * 获取默认的sessionCode
     * @param $code
     * @return string
     * @date 2021-01-21 10:22
     */
    static private function createSessionCode($code)
    {
        $sessionCode = $code ? $code : self::$defualt_code;
        return $sessionCode;
    }
}
